<?php

declare(strict_types=1);
/**
 * 作者：薛原
 * 功能：用户信息控制器
 * 时间：2025/10/17
 */
namespace App\Controller\v1;

use App\Service\UserProfilesService;
use App\Service\UserService1;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Middleware;

//token认证中间件
#[Middleware(\App\Middleware\TokenMiddleware::class)]

#[Controller(prefix: "/api/v1/users")]
class UserController extends AbstractController
{
    #[Inject]
    private UserService1 $userService;

    #[Inject]
    private UserProfilesService $userProfilesService;

    /**
     * 用户信息获取
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("baseInfo")]
    public function baseInfo(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $params = $this->parseParams($request);
        $id = $params['id'];
        try{
            $user_data = $this->userService->getUserById($id);
            $user_profiles_data = $this->userProfilesService->getUserProfiles($id);
            $ret = ["user_data"=>$user_data,"user_profiles_data"=>$user_profiles_data];

        }catch (\App\Exception\BusinessException $e){
            return $this->fail(40002,"请求失败",["errors"=>$e->getMessage()]);
        }
        return $this->success($ret,"请求成功");
    }

    /**
     * 用户资料更新接口
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[PutMapping("profile")]
    public function profile(RequestInterface $request): array|\Psr\Http\Message\ResponseInterface
    {
        $user_id = Context::get("login_user_id")."";
        $params = $this->parseParams($request);
        $this->getFullUserData($user_id);
        $data = $params;
        try{
            Db::beginTransaction();
            $this->userService->updateUser($data,$user_id);
            $this->userProfilesService->updateUserProfiles($data,$user_id);
            Db::commit();

        }catch (\App\Exception\BusinessException $e){
            Db::rollBack();
            return $this->fail(40002,"请求失败",["errors"=>json_decode($e->getMessage(),true)]);
        }
        $ret = $this->getFullUserData($user_id);
        return $this->success($ret,"更新成功");
    }

    /**
     * 返回统一包含格式的用户信息
     * @param $user_id
     * @return array
     */
    private function getFullUserData($user_id): array
    {
        $data = $this->userService->getUserById($user_id);
        unset($data["password"]);

        $profiles = $this->userProfilesService->getUserProfiles($user_id);
        $data['profile'] = $profiles;
        return $data;

    }
}
